<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no">
    <title>聊天</title>
    <link rel="stylesheet" href="/Public/jqweui/css/weui.min.css">
    <link rel="stylesheet" href="/Public/jqweui/css/jquery-weui.css">
    <link rel="stylesheet" href="/Public/layui/css/layui.mobile.css" media="all">
    <style>
        .layim-chat-main .layim-chat-text .hongbao img.layui-layim-photos{
            height: 32px;
            padding: 5px 0px;
            width: auto;
        }
        .layim-chat-text .hongbao img {
            float: left;
            max-width: 100%;
            vertical-align: middle;
            width: auto;
            height: 32px;
        }
        .hongbao .hongbao-right {
            font-size: 10px;
            padding-left: 8px;
            float: left;
            height: 100%;
            line-height: 18px;
            /*color: white;*/
        }
        .layim-chat-mine .layim-chat-text {
            background-color: #9eea6a !important;
            color: black !important;
        }

        .send-div-box {
            width: 100%;
            padding: 20px;
        }
        .weui-toast{
            z-index: 198910141;
        }
        .weui-toptips {
            z-index: 198910141;
        }

        .layim-chat-tool .layim-tool-hongbao img{
            height: 26px;
            width: auto;
            text-align: center;
            position: relative;
            top: -8px;
        }
        .weui-photo-browser-modal-visible {
            z-index: 9999999999;
        }
        .weui-photo-browser-modal .photo-container img {
            max-width: 100%;
            margin-top: -30px;
            width: 100%;
            height: auto;
        }
        .layui-layim-face {
            max-height: initial !important;
        }
        .clearfix::before,
        .clearfix::after {
            content: ".";
            display: block;
            height: 0;
            visibility: hidden;
        }
        .clearfix:after {clear: both;}
        .clearfix {zoom: 1;}
        .i-pop-members .weui-label {
            width: 66px !important;
        }
        .layim-chat-main .layim-chat-text img.layui-layim-photos{
            width: 100px;
            height: 100px;
        }
    </style>
</head>
<body>
<script src="/Public//jqweui/js/jquery-2.1.4.js"></script>
<script src="/Public//jqweui/js/jquery-weui.min.js"></script>
<script src="/Public//jqweui/js/swiper.js"></script>
<script src="/Public/layui/layui.js"></script>
<script>

    layui.use('mobile', function(){
        layui.data('layim-mobile', null);
        //用户uid;
        var  uid = "{$uid}";
        var  tel = "{$tel}";
        var  avatar = "{$avatar}";
        var  register_name = "{$register_name}";
        var  mobile = layui.mobile;
        var  layim = mobile.layim;
        var  layer = mobile.layer;
        //基础配置
        layim.config({
            init: {
                //设置我的基础信息
                mine: {
                    "username": register_name //我的昵称
                    ,"id": uid //我的ID
                    ,"avatar": avatar //我的头像
                }
            },
            brief: true,
            //上传图片接口（返回的数据格式见下文）
            uploadImage: {
                url: '/index.php/Home/Chat/uploadImg' ,         //接口地址
                type: 'post'     //默认post
            },
            maxLength: 2000,
            isNewFriend: false
        });

        var isAndriod = navigator.userAgent.toLowerCase().match(/android/i) == "android";
        setTimeout(function () {
            if (isAndriod)
            {
                $('#iupload').hide();
                $('#iuploadImg').attr('layim-event', '');
                $('#iuploadImg').on('click', function () {
                    window.upload.upload2();
                })
            }

        });

        //avatar 为上传完成图片路径
        window.uploadImage = function(avatar)
        {
            layim.selfupload(avatar);
        }

        //建立WebSocket通讯
        var socket = new WebSocket("ws://47.75.58.91:7272");
        //获取最新的聊天记录复制给layim 聊天记录从后台获取
        var historyMessage = {$history};

        var myselflocal = {};
        myselflocal.chatlog = {};
        myselflocal.chatlog['groupgroup'] = historyMessage;
        layui.data('layim-mobile', {
            key: uid,
            value:myselflocal
        });
        //连接成功时触发
        socket.onopen = function(){
            var loginData = JSON.stringify({
                type : 'init',
                uid: uid,
                username: register_name,
                avatar:  avatar
            });
            console.log('握手成功');
            socket.send(loginData);
        };

        //监听收到的消息
        socket.onmessage = function(res){
            var data = JSON.parse(res.data);
            switch (data.type) {
                // 服务端ping客户端
                case 'ping':
                    socket.send('{"type":"ping"}');
                    break;
                // 登录 更新用户列表
                case 'chatMessage':
                    layim.getMessage(data.data);
                    break;
            }
        };

        var groupName = "{$name}";

        //自定义群聊类型 group为群组唯一标识
        layim.chat({
            name: groupName //名称
            ,type: 'group' //聊天类型
            ,id: 'group' //定义唯一的id方便你处理信息
        });

        //监听返回  已修改源码
        layim.on('back', function(othis, index){
            //如果是首页 那么需要返回主界面
            if(index == 0) {
                history.back();
            }

        });

        //获取当前聊天面板高度
        setTimeout(function () {
            var ulheight = $('.layui-m-layer .layim-chat-main ul').height();
            $('.layui-m-layer .layim-chat-main ul').parent().scrollTop(ulheight);
        }, 1);

        //查看头像大图
        $('body .layim-chat-main').on('click', 'img',function (e) {
            var src = $(this).attr('src');
            var pb1 = $.photoBrowser({
                items: [
                   src
                ]
            });
            pb1.currentScale = 100;
            pb1.open();
        })
        //聊天历史处理逻辑
        //监听查看更多记录
        layim.on('chatlog', function(data, ul){
            var first = ul.children('li').eq(0);
            var first_time = first.attr('history-time');

            if (first_time === undefined) {
                first_time = layui.data('layim-mobile')[uid]['chatlog']['groupgroup'][1]['timestamp'];
                first_time = parseInt(first_time)/1000;
            }

            first_time = parseInt(first_time);
            var index = layer.open({type: 2,content: '获取中',shadeClose:false,shade: 'background-color: rgba(0,0,0,.3)'});
            $.ajax({
                type: "POST",
                url: '/index.php/Home/Chat/getHistoryMessage',
                dataType: 'json',
                data: {
                    time: first_time
                },
                success: function(res){
                    if (res.status == 1) {
                        if (res.data.length == 0) {
                            $.toptip('没有更多聊天记录', 2000, 'error');  //设置显示时间*/
                        }
                        addHistory(ul, res.data)
                    } else {
                        $.hideLoading();
                        $.toptip(res.info, 2000, 'error');  //设置显示时间*/
                    }

                    layer.close(index);
                }
            });
        });

        //循环添加聊天记录
        function addHistory(ul, history) {
            var html = ['<li history-time="{{d.history.timestamp}}" class="layim-chat-li{{ d.history.mine ? " layim-chat-mine" : "" }}" >'
                ,'<div class="layim-chat-user"><img src="{{ d.history.avatar }}"><cite>'
                ,'{{ d.history.username||"佚名" }}'
                ,'</cite></div>'
                ,'<div class="layim-chat-text">{{ layui.data.content(d.history.content||"&nbsp;") }}</div>'
                ,'</li>'].join('');

            layui.each(history, function (i, history) {
                $child = layui.laytpl(html).render({
                    history: history
                });

                ul.prepend($child)
            })

        }


        //layim建立就绪
        layim.on('sendMessage', function(res){
            // 发送消息
            var mine = JSON.stringify(res.mine);
            var to = JSON.stringify(res.to);
            var login_data = '{"type":"chatMessage","data":{"mine":'+mine+', "to":'+to+'}}';
            socket.send( login_data );
        });

        //监听红包点击事件 领取红包
        $('body .layim-chat-group').on('click', '.hongbao', function () {
            //发红包人的id
            var  send_id = $(this).data('uid');
            var  hongbao_id = $(this).data('hongbaoid');
            var index = layer.open({type: 2,content: '领取中',shadeClose:false,shade: 'background-color: rgba(0,0,0,.3)'});
            //请求后台领取红包
            $.ajax({
                type: "POST",
                url: '/index.php/Home/Chat/getHongbao',
                dataType: 'json',
                data: {
                    send_id: send_id,
                    hongbao_id: hongbao_id
                },
                success: function(res){
                    layer.close(index);
                    //标识领取成功
                    if (res.status == 1) {
                        getHongbaoSuccess(res.data);
                    } else { //标识领取失败
                        getHongbaoError(res);
                    }
                }
            });

        });

        //标识领取红包成功的逻辑
        function getHongbaoSuccess(data) {

            layer.open({
                title: [
                    '领取红包',
                    'background-color: #FF4351; color:#fff;font-size: 14px;height:44px;line-height:44px;'
                ],
                style:'width: 70%;',
                content: '<div style="color: red">恭喜您！获得' +
                data.data.money/100 + '元红包'+
                '</div>'
            });
        }
        //标识领取红包失败的逻辑
        function getHongbaoError(data) {
            layer.open({
                content: data.info
                ,skin: 'msg'
                ,time: 2 //2秒后自动关闭
            });
        }

        //监听自定义工具栏点击，以上述扩展的工具为例
        layim.on('tool(hongbao)', function(insert, send, obj){ //事件中的tool为固定字符，而code则为过滤器，对应的是工具别名（alias）
            var getTpl = hongbao.innerHTML;

            layim.panel({
                title: '发红包'
                ,tpl: getTpl
                ,data: { //数据
                }
            });

            //当创建了panel以后 自定义一个事件
            $('body').one('myShutDown', function (event, othis) {
                closePanel(othis);
            })
        });

        //关闭弹层方法
        function  closePanel(othis) {
            var othis = $(othis);
            var layero = othis.parents('.layui-m-layer').eq(0)
                ,index = layero.attr('index')
                ,PANEL = '.layim-panel';
            setTimeout(function(){
                layer.close(index);
            }, 300);
            othis.parents(PANEL).eq(0).removeClass('layui-m-anim-left').addClass('layui-m-anim-rout');
            layero.prev().find(PANEL).eq(0).removeClass('layui-m-anim-lout').addClass('layui-m-anim-right');
        }

        //监听点击“新的朋友”
        layim.on('detail', function(data){
            //以查看群组信息（如成员）为例
            $.get('/index.php/Home/Chat/getMembers', function(res){
                var getTpl = group_members.innerHTML;
                layim.panel({
                    title: '群成员' //标题
                    ,tpl: getTpl
                    ,data: {
                        list: res.data
                    }
                });
            });
        });
        $('body').on('change', '#change-type',function () {
            var value = this.value;
            if(value == 1) {
                $('#hongbao-num').show();
                $('#show-person-phone').hide();
            } else {
                $('#hongbao-num').hide();
                $('#show-person-phone').show();
            }
        });
        var sendHongbao = '{:U("sendHongbao")}';

        $('body').on('click', '#create-hongbao',function () {
            var that = this; //保存事件用于关闭弹出层
            var data = {};
            var sendHongbao = '/index.php/Home/Chat/sendHongbao';
            data.money = $('input[name = money]').val();
            data.num = $('input[name = num]').val();
            data.remark = $('input[name = remark]').val();
            data.type = $('select[name = select-type]').val();
            data.phone = $('input[name = phone]').val();
            $.showLoading('创建红包中');

            $.ajax({
                type: "POST",
                url: sendHongbao,
                dataType: 'json',
                data: data,
                success: function(res){
                    if (res.status == 1) {
                        $.hideLoading();
                        $.toptip(res.info, 2000, 'success');  //设置显示时间
                        setTimeout(function () {
                            $("body").trigger("myShutDown", [that]);
                        }, 1500);
                    } else {
                        $.hideLoading();
                        $.toptip(res.info, 2000, 'error');  //设置显示时间
                    }

                }
            });
        });


    });

    function lm_update_nickname(othis) {

        var nickName = $('#nick-name').val();

        if (nickName.length < 1 || nickName.length > 10) {
            $.toptip('群昵称为1到10个字符', 2000, 'error');  //设置显示时间
            return;
        }
        $.showLoading('正在修改...');
        $.ajax({
            type: "POST",
            url: '/index.php/Home/Chat/setNickName',
            dataType: 'json',
            data: {
                nickName: nickName,
            },
            success: function(res){
                if (res.status == 1) {
                    $.toptip('修改成功', 2000, 'success');  //设置显示时间
                    setTimeout(function () {
                        window.location.reload();
                    }, 1000)
                } else {
                    $.toptip(res.info, 2000, 'error');  //设置显示时间
                }
                $.hideLoading();
            }
        });
    }
</script>
<script id="group_members" type="text/html">
    <div style="padding: 10px; font-size: 12px;" class="i-pop-members">
        <div class="weui-cells weui-cells_form" style="margin-top: inherit;margin-bottom: 10px;">
            <div class="weui-cell" style="padding: 4px 15px;">
                <div class="weui-cell__hd"><label class="weui-label">群昵称</label></div>
                <div class="weui-cell__bd">
                    <input class="weui-input" type="text"  placeholder="请输入群昵称" value="{$register_name}" id="nick-name">
                </div>
                <a href="javascript:;" class="weui-btn weui-btn_mini weui-btn_default"  onclick="lm_update_nickname()">修改</a>
            </div>
        </div>
        <div class="clearfix" style="margin-bottom: 15px;">
            {{#  layui.each(d.data.list, function(index, item){ }}
            <div class="" style="float:left;width: 20%;margin-bottom: 10px;">
                <div style="width: 40px;height: 40px;margin: 0 auto;">
                    <img src="{{item.headimg}}" style="display: block;width: 100%;height: 100%;"/>
                </div>
                <p style="text-align: center;width: 100%; overflow:hidden;word-break:keep-all;white-space:nowrap;text-overflow:ellipsis;">
                    {{item.register_name}}
                </p>
            </div>
            {{#  }); }}
        </div>
    </div>
</script>
<!--下面为模板-->
<script id="hongbao" type="text/html">
    <form id="hongbaoForm">
        <div class="weui-cells weui-cells_form" style="padding: 10px;">
            <div class="weui-cell">
                <div class="weui-cell__hd"><label class="weui-label">总金额</label></div>
                <div class="weui-cell__bd">
                    <input class="weui-input" type="number" name="money" placeholder="0.00元">
                </div>
            </div>
            <div class="weui-cell weui-cell_select">
                <div class="weui-cell__bd">
                    <select class="weui-select" name="select-type" id="change-type">
                        <option selected="" value="1">群红包</option>
                        <option value="2">个人红包</option>
                    </select>
                </div>
            </div>
            <div class="weui-cell" id="hongbao-num">
                <div class="weui-cell__hd"><label class="weui-label">红包个数</label></div>
                <div class="weui-cell__bd">
                    <input class="weui-input" type="number" name="num" placeholder="红包个数">
                </div>
            </div>

            <div class="weui-cell" style="display: none" id="show-person-phone">
                <div class="weui-cell__hd"><label class="weui-label">手机号</label></div>
                <div class="weui-cell__bd">
                    <input class="weui-input" type="number" name="phone"  placeholder="个人手机号">
                </div>
            </div>
            <div class="weui-cell">
                <div class="weui-cell__hd"><label class="weui-label">留言</label></div>
                <div class="weui-cell__bd">
                    <input class="weui-input" type="input" name="remark" placeholder="恭喜发财大吉大利">
                </div>
            </div>
            <a href="javascript:;" class="weui-btn weui-btn_disabled weui-btn_warn" style="margin-top: 45px;" id="create-hongbao">确认</a>
        </div>
    </form>

</script>

</body>
</html>